<template class="firstpage">
  <div>
    <div class="boxMargin">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">品牌名称：</el-col>
              <el-col :span="14">
                <el-input v-model="searchData.brandName" placeholder="请输入品牌名称" />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="10">
            <el-row>
              <el-col :span="8" class="inputName">是否包含品牌故事：</el-col>
              <el-select v-model="searchData.hasDesc" placeholder="请选择">
                <el-option value="" label="请选择">请选择</el-option>
                <el-option value="1" label="是">是</el-option>
                <el-option value="0" label="否">否</el-option>
              </el-select>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin">
          <el-col :span="24" class="right">
            <el-button type="success" @click="onSearch">查询</el-button>
            <el-button @click="onReset">清空</el-button>
            <el-button type="primary" @click="report">导出报表</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="boxMargin">
      <el-card class="box-card">
        <div slot="header">
          <div class="contion-header" style="width:10%;">
            <span>品牌列表</span>
          </div>
          <div class="contion-header text-r" style="width:89%;">
            <el-button type="primary" size="small" @click="onAdd">新增品牌</el-button>
            <el-button type="primary" size="small" @click="onDelete('', 2)">批量删除</el-button>
          </div>
        </div>
        <div>
          <el-table
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="masterBrandId" label="ID" />
            <el-table-column prop="brandName" label="品牌名称" />
            <el-table-column prop="scope" label="品牌LOGO" width="250px">
              <template slot-scope="scope">
                <div v-if="scope.row.uploadId != undefined && scope.row.uploadId != null && scope.row.uploadId != ''" class="display-img">
                  <img :src="scope.row.extDomain + scope.row.imagePreview + scope.row.uploadId + scope.row.imageTemplate" alt="" style="max-width: 100%;max-height: 100%;">
                </div>
              </template>
            </el-table-column>
            <el-table-column label="是否包含品牌故事">
              <template slot-scope="scope">
                <span v-if="scope.row.hasDesc == 0">否</span>
                <span v-else-if="scope.row.hasDesc == 1">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="onInfo(scope.row)">查看</el-button>
                <el-button type="text" @click="onUpdate(scope.row)">编辑</el-button>
                <el-button type="text" @click="onDelete(scope.row, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div class="marginTop20 center">
      <template>
        <PAGER ref="wptxPager" @search="onChangePage" />
      </template>
    </div>
    <el-dialog :title="customData.isShow == true ? '编辑品牌' : '新增品牌'" :visible.sync="dialogData.dialogVisible" center width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item v-if="customData.isShow" label="品牌ID:">
          <el-col :span="10">{{ form.masterBrandId }}</el-col>
        </el-form-item>
        <el-form-item label="品牌名称:" prop="brandName">
          <el-input v-model="form.brandName" />
        </el-form-item>
        <el-form-item label="品牌LOGO:">
          <el-col :span="20">
            <div class="upLoadImg">
              <el-upload
                class="avatar-uploaders"
                action="#"
                :http-request="uploadSuccessEn"
                :show-file-list="false"
                accept=".png, .jpg"
                :before-upload="beforeUpload"
              >
                <div v-if="form.brandLogoUrl" class="display-img">
                  <img :src="form.brandLogoUrl" alt="" style="max-width: 100%;max-height: 100%;">
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <div class="rule">
                <p>尺寸：200*80px</p>
                <p>大小：小于1M</p>
                <p>格式：jpg/png</p>
              </div>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="品牌故事:" style="height:270px">
          <!-- 图片上传组件辅助-->
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action
            name="img"
            multiple
            :show-file-list="false"
            :http-request="editorImgFn"
            style="display: none;"
            accept=".png,.jpg"
          />
          <div class="edit_container">
            <quill-editor
              ref="uploads"
              v-model="form.brandDesc"
              class="editor"
              :options="editorOption"
              @change="onEditorChange($event)"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-col :span="10" />
          <el-col :span="10"><div class="txt">最多输入{{ form.addTxt ? form.addTxt: 0 }}/300000</div></el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="infoUpdate('form')">保存</el-button>
          <el-button @click="cabcleClose('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="品牌详情" :visible.sync="dialogData.isDetal" center width="50%">
      <el-row style="margin:20px 0">
        <el-col :span="6">品牌ID:</el-col>
        <el-col :span="14">{{ customData.brandDetail.masterBrandId }}</el-col>
      </el-row>
      <el-row style="margin:20px 0">
        <el-col :span="6">品牌名称:</el-col>
        <el-col :span="14">{{ customData.brandDetail.brandName }}</el-col>
      </el-row>
      <el-row style="margin:20px 0">
        <el-col :span="6">品牌LOGO:</el-col>
        <el-col :span="14">
          <div class="display-img">
            <img :src="customData.brandDetail.extDomain + customData.brandDetail.imagePreview + customData.brandDetail.uploadId" alt="" style="max-width: 100%;max-height: 100%;">
          </div>
        </el-col>
      </el-row>
      <el-row style="margin:20px 0;">
        <el-col :span="6">品牌故事:</el-col>
        <el-col :span="18" class="brandContent" :class="[customData.brandDetail.brandDesc ? 'isScroll' : '']" v-html="customData.brandDetail.brandDesc" />
      </el-row>
      <el-row style="margin:20px 0">
        <el-col :span="6">创建人:</el-col>
        <el-col :span="14">{{ customData.brandDetail.createUser }}</el-col>
      </el-row>
      <el-row style="margin:20px 0">
        <el-col :span="6">创建时间:</el-col>
        <el-col :span="14">{{ customData.brandDetail.createTime }}</el-col>
      </el-row>
    </el-dialog>
    <el-dialog title="删除品牌" :visible.sync="dialogData.isCancle" center width="50%" :before-close="cancle">
      <el-row>
        <el-col :span="4">品牌名称:</el-col>
        <el-col :span="14" style="margin-top: -15px;">
          <p v-for="(item,index) in customData.brandNameData" :key="index">{{ item }}</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">关联商品数量:</el-col>
        <el-col :span="14">{{ customData.isNum }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <p style="color:#f00">确定删除所选品牌，并处理已关联商品？</p>
          <p style="color:#f00">删除后请及时修改相关商品【品牌】信息，及品牌映射关系！</p>
        </el-col>
      </el-row>
      <el-row style="text-align:right">
        <el-col>
          <el-button type="primary" size="small" @click="onSure">确定删除</el-button>
          <el-button plain size="small" @click="cancle">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>

</template>

<script>

import $ from 'jquery'
import _validate from '../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../framework/commonJs/wptx_tools'
import _common from '../../../../framework/commonJs/wptx_common'
import _api from '../../../../framework/API/basedata'
import _allApi from '../../../../framework/API/apiAll'
import { reportingBasedata } from '../../../../framework/API/excel'
import { global } from '../../../../filter/global-api'
import { PAGER } from '@/framework/commonTemplate/'
// 富文本开始
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [
    {
      header: 1
    },
    {
      header: 2
    }
  ],
  [
    {
      list: 'ordered'
    },
    {
      list: 'bullet'
    }
  ],
  [
    {
      size: ['small', false, 'large', 'huge']
    }
  ],
  [
    {
      header: [1, 2, 3, 4, 5, 6, false]
    }
  ],
  [
    {
      color: []
    },
    {
      background: []
    }
  ],
  [
    {
      align: []
    }
  ],
  ['image']
]
// 富文本结束
const _FUNCTION_NAME = ''
export default {
  components: {
    PAGER,
    quillEditor
  },
  filters: {},
  data() {
    return {
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },

      tableData: [],

      searchData: {

        brandName: '',
        hasDesc: ''
      },

      searchDataBuffer: {

        brandName: '',
        hasDesc: ''
      },

      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },

      form: {},
      dialogData: {
        dialogVisible: false,
        isDetal: false,
        isCancle: false
      },

      historyData: {},

      infoData: {},

      customData: {
        multipleSelection: [],
        masterItemId: '',
        fileMd5: '',
        isShow: false,
        brandDetail: {},
        isCancleData: [],
        isNum: 0,
        brandNameData: [],
        brandIds: []
      },
      form: {
        masterBrandId: '',
        brandName: '',
        brandLogoUrl: '',
        brandDesc: '',
        masterBrandStoryImageCreateRequest: [],
        BrandStoryImage: {},
        addTxt: 0,
        addContent: '',
        uploadId: ''
      },
      rules: {
        brandName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    'form.addContent': function(newVal, oldVal) {
      if (this.form.addTxt > 300000) {
        this.$message({
          message: '品牌故事字数最大为300000字',
          type: 'warning'
        })
        this.form.addTxt = Number(300000)
        this.form.brandDesc = oldVal
        return
      }
    }
  },
  created() {},
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() {},
  methods: {

    onInit(data) {
      const self = this
      _api.page(self, self.pageData, self.callBack_page)
    },

    onSearch(data) {
      const self = this
      const params = self.searchData
      self.searchDataBuffer = _tools.cloneObj(self.searchData)
      self.$refs.wptxPager.resetPageNo()
      _api.page(
        self,
        self.$refs.wptxPager.pageData,
        self.callBack_page,
        params
      )
    },
    handleSelectionChange(val) {
      this.customData.multipleSelection = val
    },

    onUpdate(data) {
      const self = this
      const params = {
        masterBrandId: data.masterBrandId
      }
      self.form.masterBrandId = data.masterBrandId
      _api.brandUpdateShow(self, params, self.callback_brandUpdateShowFn)
    },
    onDelete(data, type) {
      const self = this; let params = {}; const num = []
      self.customData.brandNameData = []
      self.customData.brandIds = []
      if (type == 1) {
        self.customData.brandNameData.push(data.brandName)
      } else if (type == 2) {
        if (_validate.checkListEmpty(self.customData.multipleSelection)) {
          _tools.openTip(self, '请先选择品牌', 'warning')
          return false
        } else {
          self.customData.multipleSelection.filter((item) => {
            self.customData.brandNameData.push(item.brandName)
          })
          self.customData.multipleSelection.forEach((item) => {
            num.push(item.masterBrandId)
          })
        }
      }
      self.dialogData.isCancle = true
      self.customData.brandIds = type == 1 ? [data.masterBrandId] : num
      params = {
        brandIds: self.customData.brandIds
      }
      _api.brandCheck(self, params, self.callBack_brandCheck)
    },
    onSure() {
      const self = this; let params = {}
      params = {
        brandIds: self.customData.brandIds
      }
      _api.brandDelete(self, params, self.callBack_brandDelete)
    },

    onChangePage(data) {
      const self = this
      const params = self.searchDataBuffer
      _api.page(
        self,
        self.$refs.wptxPager.pageData,
        self.callBack_page,
        params
      )
    },

    onReset(data) {
      const self = this
      _tools.reset(self.searchData)
      _tools.reset(self.searchDataBuffer)
      self.tableData = []
      self.onInit()
    },
    // 导出报表
    report() {
      const self = this
      let params = {}
      const num = []
      if (self.customData.multipleSelection.length == 0) {
        params = self.searchData
      } else {
        self.customData.multipleSelection.forEach(item => {
          num.push(item.masterBrandId)
        })
        params.ids = num.join(',')
      }
      const time = _tools.getTime()
      const title = 'brand_' + time + '.xlsx'
      reportingBasedata(params).then(res => {
        if (!_validate.checkEmpty(res.data)) {
          _validate.downloadNotFileName(res, title)
        }
      }).catch(error => {
      })
    },
    // 品牌LOGO
    beforeUpload(res, file) {
      const self = this
      const extName = _tools.getFileExtName(res.name)
      const AllUpExt = '.png|.jpg|'
      const isLt10M = res.size / 1024 / 1024 < 1
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过1MB', 'warning')
        return isLt10M
      }
      const isSize = new Promise((resolve, reject) => {
        const width = 200
        const height = 80
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          const valid = img.width <= width && img.height <= height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(res)
      }).then(() => {
        return res
      }, () => {
        self.$message.error('上传的图片必须是等于或小于200*80!')
        return Promise.reject()
      })
      return isSize
    },
    // 上传图片成功
    uploadSuccessEn(file) {
      const self = this
      const fd = new FormData()
      fd.append('file', file.file)
      const url = 'portalapi/basedata/brand/upload'
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        if (res.code != 200) {
          _validate.openTip(self, res.message, 'error')
        } else {
          _validate.openTip(self, '图片上传成功', 'success')
          if (!_validate.checkEmpty(res.result)) {
            self.form.brandLogoUrl = res.result.data.brandLogoUrl
            self.form.uploadId = res.result.data.uploadId
            self.form.fileMd5 = res.result.data.fileMd5
          }
        }
      },
      function(error) {
        _validate.openTip(self, error.statusText, 'error')
      }
      )
    },
    // 富文本插入图片前
    editorImgFn(file) {
      const self = this
      self.uploadSuccess(file.file)
    },
    // 上传图片成功
    uploadSuccess(file) {
      const self = this
      const quill = self.$refs.uploads.quill
      const fd = new FormData()
      fd.append('file', file)
      const url = 'portalapi/basedata/brand/upload'
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        if (res.code != 200) {
          _validate.openTip(self, res.message, 'error')
        } else {
          _validate.openTip(self, '图片上传成功', 'success')
          if (res.result.data) {
            const length = quill.getSelection().index
            // 插入图片  res.info为服务器返回的图片地址
            quill.insertEmbed(length, 'image', res.result.data.brandLogoUrl)
            self.form.BrandStoryImage = {
              fileMd5: res.result.data.fileMd5,
              imageUrl: res.result.data.brandLogoUrl,
              uploadId: res.result.data.uploadId
            }
            self.form.masterBrandStoryImageCreateRequest.push(self.form.BrandStoryImage)
            // 调整光标到最后
            quill.setSelection(length + 1)
          }
        }
      },
      function(error) {
        _validate.openTip(self, error.statusText, 'error')
      }
      )
    },

    onAdd(data) {
      const self = this
      _tools.reset(self.form)
      self.dialogData.dialogVisible = true
      self.customData.isShow = false
      self.$nextTick(() => {
        self.$refs['form'].resetFields()
      })
    },

    infoUpdate(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {
            uploadId: self.form.uploadId,
            fileMd5: self.form.fileMd5,
            brandLogoUrl: self.form.brandLogoUrl,
            brandDesc: self.form.brandDesc,
            previewInfo: self.form.previewInfo,
            brandName: self.form.brandName,
            masterBrandStoryImageCreateRequest: self.form.masterBrandStoryImageCreateRequest || []
          }
          if (!self.customData.isShow) {
            _api.infoCreate(self, params, self.callBack_save)
          } else {
            const params = {
              masterBrandId: self.form.masterBrandId,
              uploadId: self.form.uploadId,
              fileMd5: self.form.fileMd5,
              brandLogoUrl: self.form.brandLogoUrl,
              brandDesc: self.form.brandDesc,
              previewInfo: self.form.previewInfo,
              brandName: self.form.brandName,
              masterBrandStoryImageCreateRequest: self.form.masterBrandStoryImageCreateRequest || []
            }
            _api.brandUpdate(self, params, self.callback_brandUpdate)
          }
        } else {
          return false
        }
      })
    },

    onInfo(data) {
      const self = this
      const params = {
        masterBrandId: data.masterBrandId
      }
      _api.infoDetail(self, params, self.callBack_infoDetail)
    },

    callBack_page(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, _tools.getErrMsg(data), 'warning')
      } else {
        self.tableData = data.result
        self.$refs.wptxPager.updatePageData(data)
      }
    },
    callBack_save(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, _tools.getErrMsg(data), 'warning')
      } else {
        // self.customData.masterBrandStoryImageCreateRequest = [];
        self.dialogData.dialogVisible = false
        self.onChangePage()
      }
    },
    callBack_infoDetail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, _tools.getErrMsg(data), 'warning')
      } else {
        self.dialogData.isDetal = true
        self.dialogData.dialogVisible = false
        self.customData.brandDetail = data.data
      }
    },
    callback_brandUpdateShowFn(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, _tools.getErrMsg(data), 'warning')
      } else {
        self.customData.isShow = true
        self.dialogData.dialogVisible = true
        self.dialogData.isDetal = false
        self.$nextTick(() => {
          self.$refs['form'].resetFields()
          self.form.uploadId = data.data.uploadId
          self.form.brandName = data.data.brandName
          self.form.brandDesc = data.data.brandDesc
          self.form.createTime = data.data.createTime
          self.form.createUser = data.data.createUser
          self.form.fileMd5 = data.data.fileMd5
          self.form.masterBrandId = data.data.masterBrandId
          self.form.brandLogoUrl = data.data.extDomain + data.data.imagePreview + data.data.uploadId
        })
      }
    },
    callback_brandUpdate(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, _tools.getErrMsg(data), 'warning')
      } else {
        _validate.openTip(self, '编辑成功', 'success')
        self.dialogData.dialogVisible = false
        self.dialogData.isDetal = false
        self.form.masterBrandStoryImageCreateRequest = []
        self.onChangePage()
      }
    },
    callBack_brandCheck(res) {
      if (res == null) {
        return false
      }
      const self = this
      if (res.code == 200) {
        if (_validate.checkListEmpty(res.result.data.data.masterBrandCasItem)) {
          self.customData.isCancleData = []
          self.customData.isNum = 0
        } else {
          self.customData.isCancleData = res.result.data.data.masterBrandCasItem
          self.customData.isNum = res.result.data.data.masterBrandCasItem.length
        }
      } else {
        _tools.openTip(self, res.message, 'error')
      }
    },
    callBack_brandDelete(res) {
      if (res == null) {
        return false
      }
      const self = this
      if (res.code == 200) {
        _tools.openTip(self, '删除成功', 'success')
        self.dialogData.isCancle = false
        self.customData.brandIds = []
        self.customData.isCancleData = []
        self.customData.isNum = 0
        self.onInit()
      } else {
        _tools.openTip(self, res.message, 'error')
      }
    },
    onEditorChange(e) {
      if (e.text) {
        this.form.addTxt = e.text.length - 1
        this.form.addContent = e.text
        if (this.form.addTxt > 300000) {
          this.form.addTxt = Number(300000)
        }
      } else {
        this.form.addTxt = 0
        this.form.addContent = ''
      }
    },
    cabcleClose(formName) {
      this.dialogData.dialogVisible = false
      this.dialogData.isDetal = false
      this.$refs[formName].resetFields()
    },
    cancle() {
      const self = this
      self.dialogData.isCancle = false
      self.customData.brandIds = []
      self.customData.isCancleData = []
      self.customData.isNum = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.upLoadImg{
    width: 100%;
    display: flex;
    align-items: center;
    .rule{
      line-height: 10px;
      margin-left: 20px;
    }
}
.editor{
    height: 200px;
}
.contion-header {
  display: inline-block;
  box-sizing: border-box;
}
.text-r {
  text-align: right;
}
.tree-div {
  position: absolute;
  height: auto;

  z-index: 10;
  overflow-y: scroll;
  width: 58%;
  background: #eee;
}
.tree {
  max-height: 200px;

  background: #eee;
}
.el-card {
  overflow: visible;
}
.avatar-uploaders{
  width: 200px;
  height: 80px;
  border: 1px solid #ccc;
}
.avatar-uploaders .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploaders .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 200px;
    height: 80px;
    display: block;
    border-radius: 8px;
  }
  .brandContent{
    word-break: break-word;
    p{
      img{
        width: 100%!important;
        height: auto;
      }
    }
  }
  .isScroll{
    height:auto;
    max-height:220px;
    overflow:hidden;
    overflow-y:scroll;
  }
  img {
    border-style: none;
    width: 100%!important;
    height: auto;
}
.display-img{
    width: 200px;
    height: 80px;
    border-radius: 6px;
    text-align: center;

}
</style>
